﻿using Newtonsoft.Json;
using Ocr.Service.Common;
using Ocr.Service.Model.Tencent;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;

namespace XKPlatform.Common
{
    /// <summary>
    /// 腾讯图片识别
    /// </summary>
    public class OcrTencent
    {

        /// <summary>
        /// 获取接口请求签名
        /// </summary>
        /// <param name="appKey">应用密钥</param>
        /// <param name="paramArray">参数列表</param>
        /// <returns></returns>
        public string GetRequestSign(string appKey, Dictionary<string, string> paramArray)
        {
            var result = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(appKey) == true)
                {
                    throw new ArgumentNullException("appKey");
                }

                //1、将<key, value> 请求参数对按key进行字典升序排序，得到有序的参数对列表N
                var paramList = paramArray.Where(c => string.IsNullOrEmpty(c.Value) == false
                                            && c.Key != "sign")
                                        .OrderBy(c => c.Key)
                                        .ToList();

                //2、将列表N中的参数对按URL键值对的格式拼接成字符串，得到字符串T（如：key1 = value1 & key2 = value2），URL键值拼接过程value部分需要URL编码，URL编码算法用大写字母，例如 % E8，而不是小写 % e8
                var paramString = string.Join("&",
                                            paramList.Select(c
                                                        => string.Format("{0}={1}",
                                                            c.Key,
                                                            CommonHelper.UrlEncode(c.Value, Encoding.UTF8)
                                                        //HttpUtility.UrlEncode(c.Value, Encoding.UTF8))
                                                        ))
                                            );

                //3、将应用密钥以app_key为键名，组成URL键值拼接到字符串T末尾，得到字符串S（如：key1 = value1 & key2 = value2 & app_key = 密钥)
                paramString = string.Format("{0}&app_key={1}", paramString, appKey);

                //4、对字符串S进行MD5运算，将得到的MD5值所有字符转换成大写，得到接口请求签名
                result = CommonHelper.Md5(paramString).ToUpper();
            }
            catch (Exception exception)
            {
                result = string.Empty;
            }

            return result;
        }


        /// <summary>
        /// 识别图片
        /// </summary>
        /// <param name="appId">腾讯接口APPID</param>
        /// <param name="appKey">腾讯接口APPKey</param>
        /// <param name="imagePath">图片本地路径</param>
        /// <returns></returns>
        public TencentDistinguishResult Distinguish(double appId, string appKey, string imagePath)
        {
            var result = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(appKey) == true
                    || string.IsNullOrEmpty(imagePath) == true)
                {
                    throw new ArgumentNullException("Distinguish函数参数不能为空！");
                }

                //获取参数值
                var timeStamp = CommonHelper.GetTimeStamp();//时间戳
                var nonceString = CommonHelper.GetNonceString();//随机字符串

                //获取图片Base64编码字符串,原始图片的base64编码数据（原图大小上限1MB，支持JPG、PNG、BMP格式）
                var imageBase64String = Convert.ToBase64String(System.IO.File.ReadAllBytes(imagePath));

                //生产参数签名
                var paramDictionary = new Dictionary<string, string>();
                paramDictionary.Add("app_id", appId.ToString());
                paramDictionary.Add("time_stamp", timeStamp.ToString());
                paramDictionary.Add("nonce_str", nonceString);
                paramDictionary.Add("image", imageBase64String);

                var sign = GetRequestSign(appKey, paramDictionary);//生成签名


                //请求识别接口
                using (var client = new WebClient())
                {
                    var values = new NameValueCollection();
                    values["app_id"] = appId.ToString();
                    values["time_stamp"] = timeStamp.ToString();
                    values["nonce_str"] = nonceString;
                    values["sign"] = sign;
                    values["image"] = imageBase64String;

                    var response = client.UploadValues("https://api.ai.qq.com/fcgi-bin/ocr/ocr_generalocr", values);

                    result = Encoding.UTF8.GetString(response);
                }

                //处理接口返回结果
                return JsonConvert.DeserializeObject<TencentDistinguishResult>(result);
            }
            catch (Exception e)
            {
                LogHelper.SaveLog("Distinguish", result);
                LogHelper.SaveLog(e);
                return null;
            }
        }



    }
}
